package com.example.swordjava;


import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;

public class Test37 {

    public static void main(String[] args) {

        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode6 = new TreeNode(6);
        TreeNode treeNode7 = new TreeNode(7);

        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode3.left = treeNode6;
        treeNode3.right = treeNode7;

        String serialize = Serialize(treeNode1);
        System.out.println(serialize);
        TreeNode treeNode = Deserialize(serialize);
        System.out.println(treeNode.val);
        System.out.println(treeNode.left.val);
        System.out.println(treeNode.right.val);
        TreeNode node3 = treeNode.right;
        System.out.println(node3.left.val);
        System.out.println(node3.right.val);


//        treeNode2.left = treeNode4;
//        treeNode3.left = treeNode5;
//        treeNode3.right = treeNode6;

    }

    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }
    }

    /**
     * 序列化二叉树
     * 请实现两个函数，分别用来序列化和反序列化二叉树，不对序列化之后的字符串进行约束，但要求能够根据序列化之后的字符串重新构造出一棵与原二叉树相同的树。
     * 二叉树的序列化(Serialize)是指：把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串，
     * 从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树等遍历方式来进行修改，
     * 序列化的结果是一个字符串，序列化时通过 某种符号表示空节点（#）
     * <p>
     * 二叉树的反序列化(Deserialize)是指：根据某种遍历顺序得到的序列化字符串结果str，重构二叉树。
     */
     static String Serialize(TreeNode root) {
        if (root == null) return "#";
        return root.val + "," + Serialize(root.left) + "," + Serialize(root.right);

    }

    static TreeNode Deserialize(String str) {
        Deque<String> queue = new LinkedList<>(Arrays.asList(str.split(",")));
        TreeNode root = build(queue);
        return root;
    }

    private static TreeNode build(Deque<String> queue) {
        String s = queue.poll();
        if ("#".equals(s)) return null;

        TreeNode root = new TreeNode(Integer.valueOf(s));
        root.left = build(queue);
        root.right = build(queue);
        return root;
    }
}
